package com.fsgom.common.web.view;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tiles.TilesContainer;
import org.apache.tiles.servlet.context.ServletUtil;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.support.JstlUtils;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.view.AbstractView;

public abstract class AbstractTilesView extends AbstractView {
	protected final String viewName;
	protected static final String TILES_RESULT_USER_BODY = "__TILES_RESULT_USER_BODY__";

	public AbstractTilesView(String viewName) {
		this.viewName = viewName;
		super.setBeanName(ClassUtils.getShortNameAsProperty(this.getClass()));
	}

	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response, String definition, String body) throws Exception {
		ServletContext servletContext = request.getSession().getServletContext();
		TilesContainer container = ServletUtil.getContainer(servletContext);

		if (container == null) {
			throw new ServletException("Tiles container is not initialized.");
		}

		exposeModelAsRequestAttributes(model, request);
		JstlUtils.exposeLocalizationContext(new RequestContext(request, servletContext));

		request.setAttribute(TILES_RESULT_USER_BODY, body);
		container.render(definition, request, response);
	}
}

